const { mongoose } = require('./db.js')
const { encrypt, decrypt } = require('../core/util/util')


const schema = new mongoose.Schema({
  username: {
    required: [true, '用户名必填'],
    index: true,
    type: String,
    validate: {
      validator(val) {
        return /^(?!\d+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,8}$/.test(val)
      },
      message: "用户名必须为 数字+字母 6-8位"
    },
    //唯一
    unique: true
  },
  password: {
    type: String,
    //不指定select查询不会返回
    select: false,
    required: [true, '密码必填'],
    validate: {
      validator(val) {
        return val !== '密码格式不正确'
      },
      message: "密码必须为 数字+密码(大小写) 8-12位"
    },
    set(val, schematype) {
      let isValidate = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d!.#*?&]{8,12}$/.test(decrypt(val))
      if (isValidate) {
        return encrypt(val)
      }
      return '密码格式不正确'
    }
  },
  email: {
    type: String,
    required: [true, '邮箱必填'],
    validate: {
      validator: function (val) {
        return /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(val)
      },
      message: "请输入合法邮箱地址"
    },
    unique: true
  },
  avatar: {
    type: String, //URL,
    default: "http://127.0.0.1:3000/images/avatar.png"
  },

  nikname: {
    type: String,
    validate: {
      validator: function (val) {
        return /^[0-9a-zA-Z\u0391-\uFFE5]{1,8}$/.test(val)
      },
      message: "昵称可包含 数字/英文/汉字 1-8位"
    },
    default: '用户' + ~~(Math.random() * 99999)
  },

  signature: {
    type: String,
    default: '这个人很懒, 什么都没有写 ^_^'
  }
})


let User = mongoose.model('User', schema)
// 定义方法
// 创建用户
User.createUser = async function (user) {
  try {
    const newUser = new this(user);
    await newUser.save();
    return newUser;
  } catch (error) {
    throw error;
  }
};
// 查询所有用户通过ID
User.findUserById = async function (id) {
  try {
    return await this.findById(id);
  } catch (error) {
    throw error;
  }
};
// 查询所有用户通过用户名
User.findUserByUsername = async function (username) {
  try {
    return await this.findOne({ username });
  } catch (error) {
    throw error;
  }
};
// 更新用户通过ID
User.updateUser = async function (id, updateData) {
  try {
    return await this.findByIdAndUpdate(id, updateData, { new: true });
  } catch (error) {
    throw error;
  }
};
// 删除用户通过ID
User.deleteUser = async function (id) {
  try {
    return await this.findByIdAndDelete(id);
  } catch (error) {
    throw error;
  }
};
// 验证登录
User.validateLogin = async function (username, password) {
  try {
    const user = await this.findOne({ username });
    if (!user) {
      throw createHttpError(401, 'User not found');
    }
    const isPasswordValid = decrypt(password) === decrypt(user.password);
    if (!isPasswordValid) {
      throw createHttpError(401, 'Invalid password');
    }
    return user;
  } catch (error) {
    throw error;
  }
};
// 验证用户名是否已存在
User.validateUsername = async function (username) {
  try {
    const user = await this.findOne({ username });
    if (user) {
      throw createHttpError(409, 'Username already exists');
    }
  } catch (error) {
    throw error;
  }
};
// 验证邮箱是否已存在
User.validateEmail = async function (email) {
  try {
    const user = await this.findOne({ email });
    if (user) {
      throw createHttpError(409, 'Email already exists');
    }
  } catch (error) {
    throw error;
  }
};
// 验证昵称是否已存在
User.validateNikname = async function (nikname) {
  try {
    const user = await this.findOne({ nikname });
    if (user) {
      throw createHttpError(409, 'Nikname already exists');
    }
  } catch (error) {
    throw error;
  }
};
// 验证密码是否正确
User.validatePassword = async function (password, user) {
  try {
    const isPasswordValid = decrypt(password) === decrypt(user.password);
    if (!isPasswordValid) {
      throw createHttpError(401, 'Invalid password');
    }
  } catch (error) {
    throw error;
  }
};
// 调用一个异步方法
// (async () => {
//   try {
//     const newUser = await User.createUser({ username: '9999pyp', password: encrypt('9999pyP.'), email: '202740708@example.com' });
//     console.log(newUser);
//   } catch (error) {
//     console.error(error);
//   }
// })();
(async () => {
  try {
    const newUser = await User.find();
    console.log('newUser', newUser);
  } catch (error) {
    console.error(error);
  }
})();
module.exports = User
